$(function () {

    //指定布局高度
    // var h=$(document).height()-$("#toolbar").height()-20;
	var height = window.parent.document.getElementById('iframe_box').offsetHeight;
	$('body').css('height',height);

    //初始化部门树
    initDept();
});


//初始化部门树
function initDept() {

    <!--ztree设置参数-->
    var setting = {
        data: {
            key: {
                name: "FNAME"
            },
            simpleData: {
                enable: true
                ,idKey: "FCODE",
                pIdKey: "FPARENT",
                rootPId: ""
            }
        },
        view:{
            showLine: false
            ,showIcon: true
        }
        ,callback: {
            onClick: function onClick(event, treeId, treeNode) {
                //初始化加载数据
				sysObj.deptCode = treeNode.FCODE;
                $('#postTable').bootstrapTable('refresh'
                    ,{
                    url:tsUtils.getRootPath()+'/post/postList'
                        ,contentType:"application/x-www-form-urlencoded",
                        queryParams:function (params) {
                            params["where"]=treeNode.FCODE;
                            return params;
                        }
                });
            }
        }
    };

	var deptSetting = {
		async:{
			enable:true,
			url:tsUtils.getRootPath()+'/getParentDepartment',
			contentType:'application/json',
			dataType:"text",
			autoParam:[]
		},
		data:{
			key:{
				name:"FNAME",
				level:"FDEPTLEVEL"
			},
			simpleData:{
				enable:true,
				idKey:"FCODE",
				level:"FDEPTLEVEL",
				pIdKey:"FPARENT",
				rootPID:9999
			}
		},
		callback:{
			onAsyncSuccess:onAsyncSuccess,
			onAsyncError:onAsyncError,
			onClick: onClick,

		}
	};

    var zTreeObj;	//tree 对象
    $.ajax({
        url:tsUtils.getRootPath()+"/public/getDeptJson"
        ,method:"post"

        ,contentType:"application/x-www-form-urlencoded"
        ,success: function(r) {
            var obj=r.msg;
            if(obj==""||obj==undefined||obj==null){
				sysObj['dept'] = r.rows;
                zTreeObj = $.fn.zTree.init($("#treeDept"), setting, r.rows);
				$.fn.zTree.init($('#parent-tree'),deptSetting,r.rows);
                //默认展开节点
                var initNode = zTreeObj.getNodes()[0];
                if(initNode.children.length>0){
                    initNode=initNode.children[0];
                }
                zTreeObj.selectNode(initNode,false,true);

                loadData(initNode.FCODE);
            }else{
                layer.alert(r.msg);
            }
        }
        ,error:function (req,status,e) {
            layer.alert(e.toString());
        }
    });
}

//加载表格数据
function loadData(selectKey) {
    var sRoot=$("#txtRootPath").val();
    var height = $('body').height()-70;

    $('#postTable').bootstrapTable({
        url			:sRoot+'/post/postList',
        method		:'post',
        striped		:true,					//是否显示间隔栏颜色
		pagination	:true,					//是否分页
		sortable	:false,					//是否启用排序
		pageSize	:5,
		pageList	:[5,10,15,20],
        contentType:"application/x-www-form-urlencoded",
		height		:height,
		columns		:[{
			title:'选中',
			field:'state',
			checkbox:true,
		},{
			field:'FROWNUM',
			title:'序号',
			align:'center',
			width:40
		},{
			field:'FCODE',
			title:'岗位代码',
			align:'center',
			width:60
		},{
			field:'FNAME',
			title:'岗位名称',
			width:120,

		},{
        	field:'FDESC',
			title:'描述',
			width:200
		},{
			field:'FORGNAME',
			title:'所属机构',
			width:120,
			align:'center'
		},{
			field:'FISSTOP',
			title:'是否停用',
			width:60,
			align:'center'
		}],
        queryParams :queryParams,
        onDblClickCell:function (field,value,row,td) {
            console.log(row);
        },
        onLoadSuccess:function (data) {

        },
        onLoadError:function (data) {
            tsUtils.handleError(data);
        }
    });

    //表格初始化查询参数
    function queryParams(params) {
        var ztree=$.fn.zTree.getZTreeObj("treeDept");
        var nodes=ztree.getSelectedNodes();
        if(nodes && nodes!=null){
            var selectKey=nodes[0].FCODE;
            params["where"]=selectKey;
        }
        return params;
    }
}

//添加岗位
function addPost() {
	$('#add-content form :input').attr('value','');
	$('#add-content form')[0].reset();
	$('#FCODE').attr('readonly',false);
	layer.open({
		type:1,
		title:'添加岗位',
		area:['600px','350px'],
		skin:'layer-window',
		shadeClose:true,
		content:$('#add-content'),
		btn:['添加','取消'],
		yes:function () {
			postData('add');
		},
	})
}

//编辑岗位
function editPost(){
	var selectArray;
	selectArray = $('#postTable').bootstrapTable('getSelections');
	if(selectArray.length >1){
		layer.alert('只能修改一项',{icon:6})
	}else{
		getPostInfo(selectArray[0].FCODE);
	}
}

function getPostInfo(fcode) {
	var data = {};
	data.fcode = fcode;
	$.ajax({
		type:'post',
		url:tsUtils.getRootPath()+'/post/getPostInfo',
		data:JSON.stringify(data),
		contentType:'application/json;charset=utf-8',
		success:function (datas) {
			doEdit(datas.rows)
		}
	});
}

//删除岗位
function delPost() {
	var selectArray;
	selectArray = $('#postTable').bootstrapTable('getSelections');
	if(selectArray.length == 0){
		layer.alert('请选择删除项',{icon:6})
	}else{
		layer.alert('确定要删除这'+selectArray.length+'项吗？',{
			time:0,
			btn:['确定','取消'],
			yes:function (index) {
				var dataArray = [];
				for(var i = 0 ; i < selectArray.length ;  i++ ){
					var object = selectArray[i];
					dataArray.push(object.FCODE);
				}
				$.ajax({
					type:'post',
					url:tsUtils.getRootPath()+'/post/deletePost',
					data:JSON.stringify(dataArray),
					contentType:'application/json;charset=utf-8',
					success:function (data) {
						if(data.msg == null){
							$('#postTable').bootstrapTable('refresh'
								,{
									url:tsUtils.getRootPath()+'/post/postList'
									,contentType:"application/x-www-form-urlencoded",
									queryParams:function (params) {
										params["where"]=sysObj.deptCode;
										return params;
									}
								});
							layer.close(index);
							layer.msg('删除成功',{time:1500});
						}else{
							layer.close(index);
							layer.msg('删除失败',{time:1500});
						}
					},
					error:function (data) {

					}
				});
			}
		})
	}

}

//打印岗位
function printPost() {
	tableUtils.init('postTable');
	tableUtils.doPrint();
}

//导出岗位
function exportPost() {
	tableUtils.init('postTable');
	tableUtils.exportTableToExcel(0);
}

//退出iframe
function exitFrame() {
	tsUtils.removeIframe();
}

//提交数据
function postData(type) {
	var formData = sysForm.getFormData('addPostForm');
	var url;
	if(type == 'add'){
		url = tsUtils.getRootPath()+'/post/addPost';
	}else if(type == 'edit'){
		url = tsUtils.getRootPath()+'/post/editPost';
	}

	$.ajax({
		type:'post',
		url:url,
		data:JSON.stringify(formData),
		contentType:'application/json;charset=utf-8',
		success:function (data) {
			layer.closeAll();
			if(type == 'add'){
				layer.msg('添加成功',{time:1500});
			}else{
				layer.msg('修改成功',{time:1500});
			}
			var treeObj = $.fn.zTree.getZTreeObj('treeDept');
			var node = treeObj.getNodeByParam('FCODE',$('#FDEPTCODE').val());
			treeObj.selectNode(node);
			$('#postTable').bootstrapTable('refresh'
				,{
					url:tsUtils.getRootPath()+'/post/postList'
					,contentType:"application/x-www-form-urlencoded",
					queryParams:function (params) {
						params["where"]=$('#FDEPTCODE').val();
						return params;
					}
				});

		},
		error:function (data) {
			layer.closeAll();
			if(type == 'add'){
				layer.msg('添加失败',{time:1500});
			}else{
				layer.msg('修改失败',{time:1500});
			}
		}
	})
}

function onAsyncSuccess(event,treeId,treeNode,msg) {
}

function onAsyncError(event,treeId,treeNode,XMLHttpRequest,textStatus,errorThrown) {
	tsUtils.handleError(XMLHttpRequest.responseText);
}

function onClick(event, treeId, treeNode) {
	$('#FDEPTNAME').val(treeNode.FNAME);
	$('#FDEPTCODE').val(treeNode.FCODE);
	$('#FORGCODE').val(treeNode.FORGCODE);
}

//显示menu
function showMenu() {
	var deptObj = $('#FDEPTNAME');
	var deptOffset = $('#FDEPTNAME').offset();
	$('#deptTree').css({left:deptOffset.left+'px',top:deptOffset.top + deptObj.outerHeight()+'px'}).slideDown('fast');
	$('body').bind('mousedown',onBodyDown);
}

function hideMenu() {
	$('#deptTree').fadeOut('fast');
	$('body').unbind('mousedown',onBodyDown);
}
function onBodyDown(event) {
	if(!(event.target.id == 'menuBtn' || event.target.id == 'deptTree' || $(event.target).parents('#deptTree').length > 0 )){
		hideMenu();
	}
}

function doEdit(data) {
	sysForm.setForm(data[0]);
	$('#FCODE').attr('readonly',true);
	layer.open({
		type:1,
		title:'修改岗位',
		area:['600px','350px'],
		skin:'layer-window',
		shadeClose:true,
		content:$('#add-content'),
		btn:['修改','取消'],
		yes:function () {
			postData('edit');
		}
	})
}

//设置权限
function setPermission() {
	var selectArray;
	var postCode;
	var postDatas= {};
	selectArray = $('#postTable').bootstrapTable('getSelections');
	if(selectArray.length == 0){
		layer.alert('请选择岗位',{icon:6});
		return
	}else if(selectArray.length > 1){
		layer.alert('只能选择一个岗位',{icon:6});
		return
	}else{
		postCode = selectArray[0].FCODE;
		postDatas.postCode = postCode;
	}

	var setting = {
		check:{
			enable:true
		},
		data:{
			key: {
				name: "FNAME"
			},
			simpleData: {
				enable: true,
				idKey: "FCODE",
				pIdKey: "FPARENT",
				rootPId: ""
			}
		},
	};


	var rightArray = null;
	$.ajax({
		type: 'post',
		url: tsUtils.getRootPath() + '/post/getRightList',
		contentType: 'application/json;charset=utf-8',
		async:false,
		success:function (data) {
			rightArray = data.rows;
		},
	});

	var postRightArray = null
	$.ajax({
		type:'post',
		url: tsUtils.getRootPath() + '/post/getPostRightList',
		contentType:'application/json;charset=utf-8',
		async:false,
		data:JSON.stringify(postDatas),
		success:function (data) {
			postRightArray = data.rows;
		}
	});

	for(var i = 0 ; i < rightArray.length ; i ++){
		for(var j = 0 ; j < postRightArray.length; j++){
			if(rightArray[i].FROLEID == postRightArray[j].FROLEID && rightArray[i].FID == postRightArray[j].FID && rightArray[i].TAG == 'op')
				rightArray[i].checked = true;
		}
	}

	layer.open({
		type:1,
		title:'设置权限',
		area:['300px','500px'],
		skin:'layer-window',
		shadeClose:true,
		content:$('#permissionTree'),
		btn:['确定','取消'],
		success:function () {
			$.fn.zTree.init($('#permission-Tree'),setting,rightArray);
		},
		yes:function () {
			var treeNode = $.fn.zTree.getZTreeObj("permission-Tree");
			var checkNodes= treeNode.getCheckedNodes(true);
			var setData= {};
			setData.postCode = postCode;
			setData.checkNodes = checkNodes;

			$.ajax({
				type:'post',
				url: tsUtils.getRootPath() + '/post/setPostRight',
				contentType:'application/json;charset=utf-8',
				async:false,
				data:JSON.stringify(setData),
				success:function (data) {
					layer.closeAll();
					layer.msg('设置成功',{time:1500});
				}
			});

		}
	})
}
